package cn.iocoder.yudao.module.promotion.service.agent;

import cn.hutool.core.io.file.FileNameUtil;
import cn.iocoder.yudao.framework.common.util.io.FileUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import cn.iocoder.yudao.module.promotion.controller.admin.agent.vo.*;
import cn.iocoder.yudao.module.promotion.dal.dataobject.agent.AgentDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.promotion.dal.mysql.agent.AgentMapper;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.*;

/**
 * 客服 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class AgentServiceImpl implements AgentService {

    @Resource
    private AgentMapper agentMapper;

    @Override
    public void updateAgent(@RequestParam String name, MultipartFile file) throws IOException {
        //转为Base64
        String base64 = FileUtils.convertToBase64(file.getBytes(), FileNameUtil.extName(file.getOriginalFilename()));

        AgentDO agent;
        List<AgentDO> agentDOList = agentMapper.selectList(Wrappers.emptyWrapper());
        if (agentDOList.isEmpty()) {
            agent = new AgentDO();
            agent.setName(name);
            agent.setQr(base64);
            agentMapper.insert(agent);
        } else {
            agent = agentDOList.get(0);
            agent.setName(name);
            agent.setQr(base64);
            agentMapper.updateById(agent);
        }
    }

    @Override
    public AgentDO getAgent() {
        AgentDO agent;
        List<AgentDO> agentDOList = agentMapper.selectList(Wrappers.emptyWrapper());
        if (agentDOList.isEmpty()) {
            return null;
        } else {
            return agentDOList.get(0);
        }
    }

    @Override
    public PageResult<AgentDO> getAgentPage(AgentPageReqVO pageReqVO) {
        return agentMapper.selectPage(pageReqVO);
    }

}